/* ************************************************************************************************

	Copyright (c) 2005-2006, IGR
	All Rights Reserved.
	Licensed under the Apache License version 2.0 or above.
	For more information on licensing, see:
        http://www.apache.org/licenses/


 ************************************************************************************************
 Objet Input code (with possible Label) with permissive value
 VERSION:0.85
 DATE:16/03/2006
 ************************************************************************************************
Init parameter :
 Name:               Code name
 top:           	 Top position (in pixel)
 left:               Left position (in pixel)             
 width:              Width 
 parent              object parent
 objPar              object of parameter
 		arrValue		 array of permissive value
 					the array is :
						-a liste of value if this.boolWithLabel=false 
						(ex: [[val1],[val2],...,[valn]])
						-a list of array which contain a couple code/label if this.boolWithLabel=true
						(ex: [[code1,label1],...,[coden,labeln]])
 		url              url to call to get the permissive value
 		alwaysRefresh	 If True and if url, the url will always be call to refresh data
 						 else the url will be call once to get the data
 		submitOnload     true to allow the popup to call the url onload.
		boolWithLabel	 True if the code input has a label protected field
        codeWidth		 width of the first code input if there is a label input           
*************************************************************************************************/


// *************************************
// CONSTRUCTOR
// *************************************
rialto.widget.codeLabel=function(codeName,top,left,width,parent,objPar){
	//base object parameter
    var objParam={
    		type:"codelib",
    		name:codeName,
    		left:left,
    		top:top,
    		width:width
    }
	
	//base constructor
	this.base = rialto.widget.AbstractComponent;    
    this.base(objParam);

	//Default value
    this.boolWithLabel=true;
    this.url = null;
    this.submitOnload=true;
    this.arrPermValue = new Array;
    
    //width of the code input
	this.codeWidth=40;
	
	this.alwaysRefresh = false;
 	this.dataLoadOnce=false;
 	
	//set the value with the properties of the objPar object
    if (objPar != null){               
        if (objPar.arrValue){
            this.arrPermValue = objPar.arrValue;        
        }        
        if (rialto.lang.isBoolean(objPar.boolWithLabel)){
            this.boolWithLabel = objPar.boolWithLabel;        
        }
        if (objPar.url){
            this.url = objPar.url;        
        }       
        if (rialto.lang.isBoolean(objPar.submitOnload)){
            this.submitOnload = objPar.submitOnload;
        }
        if (rialto.lang.isBoolean(objPar.alwaysRefresh)){
            this.alwaysRefresh = objPar.alwaysRefresh;
        }        
        if (rialto.lang.isNumber(objPar.codeWidth)){
            this.codeWidth = objPar.codeWidth!=0?objPar.codeWidth:40;        
        }         
    }
	if(!this.boolWithLabel){
		//width of the code input without second field	
		this.codeWidth=this.width-27;
	}
	//release object
	objPar=null;
	objParam=null;
	this.base=null;

    var oThis=this;  
 
    // *******************************************
	// GENERATION OF DOM ELEMENTS
	// *******************************************
 
    this.divExt.className='codeLibelle-divGen';
    this.divExt.style.width= this.width;                 
    this.divExt.style.top=this.top;        
    this.divExt.style.left=this.left;
        
    //First Input
    this.code=new rialto.widget.Text(this.name,0,0,this.codeWidth,"A",this.divExt,{autoUp:false,position:'absolute'});
    //Help image    
    this.img =new rialto.widget.Image('pinkHelpButton',this.codeWidth,-2,this.divExt,"aide",'redHelpButton',{position:'absolute'});

	if(this.boolWithLabel){
	    //Second input protected
    	this.label = new rialto.widget.Text("LIB"+this.name,0,this.codeWidth+27,this.width-(this.codeWidth+27),"A",this.divExt,{disable:true,position:'absolute'});
    	this.label.setStyle({backgroundColor:'#E2F4FF'});
	}
	
	
    //Onclick function
    this.img.onclick=function (){            
        var fen=new FenRech(oThis,this.submitOnload);
    };
     
    //ajax component 
    if(this.url){ 
	    this.remote=new rialto.io.AjaxRequest({
							url:this.url,
							method: 'get', 
							callBackObjectOnSuccess:this,
							withWaitWindow:true,
							onSuccess: this.refreshPermissiveValue
						}) 
	}
        
    //input onblur function to check data
    this.code.onblur=function (){   
        if(oThis.code.getValue()!=""){
            if (this.wchanged) {            
	                oThis.checkValue();
		   	}
        }                               
    }

    //add to the parent
    if (parent) {this.placeIn(parent);}; 
}


rialto.widget.codeLabel.prototype = new rialto.widget.AbstractComponent;


rialto.widget.codeLabel.prototype.release=function(){	
	this.code.remove();
	this.img.remove();
	this.img.onclick=null;
	if(this.boolWithLabel){
	    //Second input protected
    	this.label.remove();
    }
}


//This fonction will check the type value using Array or url
rialto.widget.codeLabel.prototype.checkValue=function(){	
	if((this.url && this.alwaysRefresh) || (this.url && !this.dataLoadOnce)){
		//call the url who check the value
		var pars = "CODE="+this.getValue();
	    this.remote.load(pars);
	}
	else{
		//check in the array of permissive value
		this.checkInPermissiveValue();
	}
}


rialto.widget.codeLabel.prototype.checkInPermissiveValue=function(){
		
		//Code value in permissive value ?
		var ind=this.indexOf(this.getValue());		
		if(ind!=-1){
			if(this.boolWithLabel){						
				this.label.setValue(this.arrPermValue[ind][1]);				
			}
			this.code.removeAsRequired();
		}
		else{
			if(this.boolWithLabel){			
				this.label.setValue("?");				
			}
			//on cercle de rouge
			info = new rialto.widget.Alert("Invalid code");
		    this.code.showAsRequired();
		    this.code.setFocus();
		}
}


rialto.widget.codeLabel.prototype.indexOf = function (obj) {
	//===================
	//return index of obj in arr or -1 if it is not in
     for (var i = 0; i < this.arrPermValue.length; i++){
			if (this.arrPermValue[i][0] == obj) {
				return i;
			}
		}
		return -1;
	}
	
	
/*
this method is use to set the permissive value
the array is :
	-a liste of value if this.boolWithLabel=false (ex: [[val1],[val2],...,[valn]])
	-a list of array which contain a couple code/label (ex: [[code1,label1],...,[coden,labeln]])
*/
rialto.widget.codeLabel.prototype.setPermissiveValue=function(arrPermValue){	
	this.arrPermValue=arrPermValue;	
}

rialto.widget.codeLabel.prototype.getValue=function(){
	return this.code.getValue();
}

//return true if the label input is filled
rialto.widget.codeLabel.prototype.isNotEmpty=function(){    
    return (this.label.getValue()!="");
}


rialto.widget.codeLabel.prototype.setValue=function(code,libelle){
    this.code.setValue(code);
    if(this.boolWithLabel){
        this.label.setValue(libelle);
    }    
    this.code.removeAsRequired();    
}


rialto.widget.codeLabel.prototype.refreshPermissiveValue=function(request){        
/*this method is use to refresh the permissive value and to check the code in the new values
the response must be an array with :
	-a liste of value if this.boolWithLabel=false (ex: [[val1],[val2],...,[valn]])
	-a list of array which contain a couple code/label (ex: [[code1,label1],...,[coden,labeln]])
*/	

	var res=eval("("+request.responseText+")");
	this.setPermissiveValue(res);
	this.checkInPermissiveValue();
	this.dataLoadOnce=true;	
}

rialto.widget.codeLabel.prototype.checkOneValue=function(request){        
/*this method is use to check only one value
the response must be an object where :
-the first parameter is a boolean indicating if the code is ok: codeOk
-the second is the label value for this code: label
*/	
	var res=eval("("+request.responseText+")");
	if(res.codeOk && this.boolWithLabel){
		this.label.setValue(res.label);
	}
	this.dataLoadOnce=true;	
}


//******those 2 METHODS ARE DEPRECATED...USE SETENABLE
//to enable
rialto.widget.codeLabel.prototype.active=function(){
	rialto.deprecated('CodeLib','active','setEnable(true)');
    this.setEnable(true);    
}
//to desable
rialto.widget.codeLabel.prototype.inactive=function(){
	rialto.deprecated('CodeLib','inactive','setEnable(false)');
    this.setEnable(false);
}
//******

//this method will allow to enable or disable the codeLabel according to the parameter
rialto.widget.codeLabel.prototype.setEnable=function(enable){
	if(enable){
		this.code.setEnable(true);   
		if(this.boolWithLabel){
			this.label.setEnable(true);
	    	this.label.setStyle({backgroundColor:'#E2F4FF'});
	   	}
	    this.img.setEnable(true);
	}
	else{
		this.setValue("","");
	    this.code.setEnable(false);   
	    if(this.boolWithLabel){this.label.setEnable(false);}
	    this.img.setEnable(false);
	}
	this.enable=enable;
}

//popup to help find permissive values

FenRech.prototype.nbreInstance=0;

function FenRech(refParent,sumitOnload){    

        this.id="FenRechCodeLib_"+FenRech.prototype.nbreInstance++;
        rialto.session.reccord(this,this.id);
        var oThis=this;

        this.refParent=refParent;

        
        this.fen = new rialto.widget.PopUp("fen",50,200,420,410,"","Help","transparent");                        
        
        this.fen.onClose=function() {
        	oThis.remove();
        }
        // Frame               
        this.CADRE1=new rialto.widget.Frame({ name    :'CADRE1',
        						top:10, left:10, width:375, height:45,
						        title   : "code/label wanted", 
						        dynamic : false ,
						        open    : true,
						        parent  : this.fen	}
        );        

        var url=this.refParent.url;                                   
        
        var obj={boolWithFenWait:true,callBackObjectOnSuccess:this,onSuccess:this.refreshData}
        
                         
        this.FORM1 = new rialto.widget.Form("FORM1",url,this.CADRE1,obj);

        oParent = this.FORM1;
        // Input code           
        this.CODE = new rialto.widget.Text("CODE",10,5,260,"A",oParent,{position:'absolute'});
        // submit button
        this.BRECH = new rialto.widget.Button(11,270,"Find","Find",oParent)        
        
        this.BRECH.onclick=function () {            
        /*=======LOADING===============*/
			if((oThis.refParent.url && oThis.refParent.alwaysRefresh) || (oThis.refParent.url && !oThis.refParent.dataLoadOnce)){
				//call the url who check the value
				 oThis.FORM1.submitForm();
			}
			else{
				//check in the array of permissive value
				oThis.arrPermValue=oThis.refParent.arrPermValue
				oThis.checkInPermissiveValue();
			}                
        };
        
        //result grid        
        if(this.refParent.boolWithLabel){
			tabEntete=["Code","Label"];    
        	tabTypeCol=[["string",85],["string",205]]; 
		}
		else{
			tabEntete=["Code"];    
        	tabTypeCol=[["string",290]]; 
		}                           

        this.tableauRes=new rialto.widget.Grid(
        	{TabEntete	: tabEntete,
        	 name		: "TabRvMvt",
        	 top		: 65,
        	 left		: 10,
        	 height		: 310,
        	 bNavig		: false,
        	 rang		: 12,
        	 tabTypeCol	: tabTypeCol,
        	 objPar		: {autoWidth:true},
        	 parent		: this.fen
        	} );                 
		
		//on click and double click functions	
		this.tableauRes.onclick=function (indLigne,indCell)
        {
            oThis.code=this.tabData[indLigne][0]; 
            oThis.lib=this.tabData[indLigne][1];                                 
        }
        this.tableauRes.ondbleclick=function (indLigne,indCell)
        {                
            var code=this.tabData[indLigne][0];
            var lib=this.tabData[indLigne][1];                 
            oThis.refParent.setValue(code,lib);
            oThis.fen.close();
        }
             
        //select button
        this.BENTR = new rialto.widget.Button(385,170,"Select","Select",this.fen)                
        this.BENTR.onclick=function () {                    
            oThis.refParent.setValue(oThis.code,oThis.lib);
            oThis.fen.close();                       
        }
        
        if (sumitOnload){
        	this.BRECH.onclick();
       	}   
}

FenRech.prototype.checkInPermissiveValue=function(){
		//check the text in the collection
		var text=this.CODE.getValue()
		var arr=new Array;
		//if text is empty collection is parent collection
		if(text==""){
			arr=this.refParent.arrPermValue;
		}
		else{			
			//else find in parent collection whet look like the text
			for (var i = 0; i < this.refParent.arrPermValue.length; i++){
				for (var j = 0; j < this.refParent.arrPermValue[i].length; j++){				
					if (this.refParent.arrPermValue[i][j].indexOf(text) != -1) {
						arr.push(this.refParent.arrPermValue[i]);						
						j=this.refParent.arrPermValue[i].length;
					}
				}
			}
		}		
		if (arr.length==0){
			info = new rialto.widget.Alert("No code match");
		} 
		//fill the grid with the collection matche 		
        this.tableauRes.fillGrid(arr);            

}
FenRech.prototype.remove=function(request){
		//this.fen.remove();
        this.BRECH.onclick=null;
	    this.BENTR.onclick=null;
        this.tableauRes.onclick=null;
        this.tableauRes.ondbleclick=null;
        this.CADRE1.remove();        
        this.BENTR.remove();
        this.tableauRes.remove();
        rialto.session.objects[this.id]=null;
 }   

FenRech.prototype.refreshData=function(request){
	//after ajax call
    var res=eval("("+request.responseText+")");
    //permissive value
    this.arrPermValue=res;   
    //fill the grid
	this.tableauRes.fillGrid(this.arrPermValue); 
	//send information to the parent
	this.refParent.arrPermValue=this.arrPermValue;
	this.refParent.dataLoadOnce=true;	    
 }   
